<?php declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\User;
use app\admin\model\UserIdcardAudit;
use app\admin\model\UserVip;
use think\facade\Db;

class UserService
{
    /**
     * 用户列表
     * @return void
     */
    public function getUserList($pageSize, $startDate, $endDate, $keywords, $vip, $gender){
        $auditService = new AuditService();
        $items = Db::name('user')->alias('u')
            ->leftJoin('user_vip v', 'u.id = v.user_id')
            ->field(['u.id','u.nickname','u.mobile','u.gender','u.avatar','u.status','u.create_time','v.expire_time'])
            ->where(function ($query) use ($startDate, $endDate, $keywords, $vip, $gender){
                if($startDate){
                    $query->where('u.create_time', '>=', strtotime($startDate));
                }
                if($endDate){
                    $query->where('u.create_time', '<=', strtotime($endDate.' 23:59:59'));
                }
                if($keywords){
                    $query->where('u.nickname|u.mobile', 'like', $keywords. '%');
                }
                if ($vip) {
                    // todo
                }
                if(isset($gender) && $gender != ''){
                    $query->where('u.gender', $gender);
                }
            })
            ->order('u.create_time desc')
            ->paginate($pageSize)->each(function($item) use ($auditService){
                $bankItem = $auditService->getBank($item['id']);
                $item['bank_no'] = $bankItem['bank_no'] ?? '';
                $item['bank_name'] = $bankItem['bank_name'] ?? '';
                $item['expire_time'] = isset($item['expire_time']) ? date("Y-m-d H:i:s") : '';
                return $item;
            });
        return $items;
    }

    /**
     * 会员
     * @param $pageSize
     * @param $userId
     * @param $keywords
     * @return void
     */
    public function getVipList($pageSize, $userId, $keywords){
        $items = Db::name('user_vip')->alias('v')
            ->leftJoin('user u', 'v.user_id = u.id')
            ->field(['u.nickname','u.mobile','u.gender','u.avatar','u.create_time','v.user_id','v.expire_time'])
            ->where('v.expire_time', '>', time())
            ->where(function ($query) use ($userId, $keywords){
                if($userId){
                    $query->where('v.user_id', $userId);
                }
                if($keywords){
                    $query->where('u.nickname|u.mobile', 'like', $keywords. '%');
                }
            })
            ->order('v.expire_time desc')
            ->paginate($pageSize);
        return $items;
    }

    /**
     * 获取用户信息
     * @param $userId
     * @return void
     */
    public function getUserProfile($userId){
        if (!$userId) {
            return [];
        }
//        $redis = RedisPackage::getInstance();
//        $userProfileKey = RedisKeyConst::getUserProfileKey($userId);
//        if (!$redis::exists($userProfileKey)) {
//            $item = $this->_getUserProfile($userId);
//        } else {
//            $item = $redis::hGetAll($userProfileKey);
//            if (!empty($item)) {
//                $item['user_auth_info'] = json_decode($item['user_auth_info'], true);
//                $item['user_skill'] = json_decode($item['user_skill'], true);
//            }
//        }

        return $this->_getUserProfile($userId);
    }

    /**
     * 获取用户信息
     * @param $userId
     * @return void
     */
    public function _getUserProfile($userId){
        $model = new User();
        $item = $model->alias('u')
            ->leftJoin('user_account account', 'u.id = account.user_id')
            ->field(['u.id as user_id','u.nickname','u.mobile','u.gender','u.avatar','u.create_time','u.status','account.balance'])
            ->where('u.id', $userId)
            ->find()
            ->toArray();
        $item['user_idcard_audit'] = $this->_getUserIdCardAudit($userId);
        $expire = (new UserVip())->getUserVipExpire($userId);
        $item['user_auth_info'] = [
            'is_auth' => 0,
            'auth_expire' => ''
        ];
        if ($expire && $expire > time()) {
            $item['user_auth_info'] = [
                'is_auth' => 1,
                'auth_expire' => date('Y-m-d H:i:s', $expire)
            ];
        }
        return $item;
    }

    /**
     * 获取用户 openid
     * @param $userId
     * @return string
     */
    public function _getUserOpenId($userId): string
    {
        $userModel = new User();
        return  $userModel->where('id', $userId)->value('openid');
    }

    /**
     * 用户实名认证状态
     * @param $userId
     * @return int
     */
    public function _getUserIdCardAudit($userId): int
    {
        $userIdCardModel = new UserIdcardAudit();
        return $userIdCardModel->where('user_id', $userId)->value('status') ? :-1;
    }

    /**
     * 获取用户认证量
     * @param string $start
     * @param string $end
     * @return void
     */
    public function getUserAuthCount(string $start = '', string $end = ''){

        $model = new UserIdcardAudit();
        if (!empty($start) && !empty($end)) {
            $count = $model->getUserAuthCount($start, $end);
        } else {
            $count = $model->getUserAuthCount();
        }

        return $count;
    }

    /**
     * 本周认证用户
     * @return void
     */
    public function getAuditUser($pageSize = PAGE_SIZE){
        return Db::name('user_vip')->alias('v')
            ->leftJoin('user u', 'v.user_id = u.id')
            ->field(['v.user_id','v.update_time','v.expire_time','u.nickname',])
            ->where(function ($query) {
                $query->where('v.expire_time', '>', time());
            })
            ->order('u.update_time desc')
            ->paginate($pageSize)
            ->each(function($item){
                $item['update_time'] = date('d H:i', $item['update_time']);
                return $item;
            });
    }
}